<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\AuditFlowStepModel;
use cmf\controller\AdminBaseController;
use think\Db;

class AuditFlowStepController extends AdminBaseController
{

    /**
     * 审核步骤列表
     * @adminMenu(
     *     'name'   => '审核步骤管理',
     *     'parent' => 'admin/AuditFlowStep/index',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 40,
     *     'icon'   => '',
     *     'remark' => '审核步骤管理',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $authId    = $this->request->param('audit_id',0,'intval');
        
        $lists = Db::name('audit_flow_step')
              -> where('audit_id','in',$authId)
              -> select()->toArray();

        foreach ($lists as $k => $v) {
            $auth_role_name = Db::name('role')->where('id','in',$v['auth_role_id'])->column('name');
            $lists[$k]['auth_role_name'] = implode(',', $auth_role_name);
        }

        $this->assign('result', $lists);
        $this->assign('audit_id', $authId);

        $actions = ['add', 'edit', 'delete'];
        $this->assign('actions', actions_check($this->request->module().'/'.$this->request->controller().'/', $actions));

        return $this->fetch();
    }

    /**
     * 添加审核步骤
     * @adminMenu(
     *     'name'   => '添加审核步骤',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加审核步骤',
     *     'param'  => ''
     * )
     */
    public function add()
    {
        $auditId    = $this->request->param('audit_id',0,'intval');

        $roleList = Db::name('role')->where('id','neq',1)->select();
        $this->assign('role_list', $roleList);

        $this->assign('audit_id', $auditId);

        return $this->fetch();
    }

    /**
     * 添加审核步骤提交
     * @adminMenu(
     *     'name'   => '添加审核步骤提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加审核步骤提交',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {
        $data     = $this->request->param();
        $audit_id = $this->request->param('audit_id','');
        $result   = $this->validate($data, 'AuditFlowStep');
        if ($result !== true) {
            $this->error($result);
        }

        $data['auth_role_id'] = implode(',', $data['auth_role_id']);
        // pre($data,1);

        $step_count         = $this->sortIndex($audit_id);   //创建步骤序号排列，并返回步骤总数
        $auditFlowStepModel = new AuditFlowStepModel();
        $data['step_index'] = $step_count+1;
        $result             = $auditFlowStepModel->validate(true)->save($data);

        if ($result === false) {
            $this->error($auditFlowStepModel->getError());
        }

        //操作日志
        admin_log($data['step_name'], 'add', 'audit_flow_step');

        $this->success("添加成功！", url("audit_flow_step/index",['audit_id'=>$data['audit_id']]));
    }

    /**
     * 编辑审核步骤
     * @adminMenu(
     *     'name'   => '编辑审核步骤',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑审核步骤',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
        $id             = $this->request->param('id');
        $auditFlowStepModel = new AuditFlowStepModel();
        $result         = $auditFlowStepModel->where('step_id', $id)->find();

        $roleList = Db::name('role')->where('id','neq',1)->select()->toArray();
        $result['auth_role_id'] = explode(',', $result['auth_role_id']);

        foreach ($roleList as $k => $v) {
            $roleList[$k]['checked']='';
            if( in_array($v['id'],$result['auth_role_id']) ){
                $roleList[$k]['checked'] = 'checked';
            }
        }

        $this->assign('role_list', $roleList);

        $this->assign('result', $result);
        $this->assign('audit_id', $result['audit_id']);
        return $this->fetch();
    }

    /**
     * 编辑审核步骤提交
     * @adminMenu(
     *     'name'   => '编辑审核步骤提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑审核步骤提交',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {
        $data           = $this->request->param();
        $result = $this->validate($data, 'AuditFlowStep');
        if ($result !== true) {
            $this->error($result);
        }

        $data['auth_role_id'] = implode(',', $data['auth_role_id']);


        $auditFlowStepModel = new AuditFlowStepModel();
        $result         = $auditFlowStepModel->validate(true)->save($data, ['step_id' => $data['step_id']]);
        if ($result === false) {
            $this->error($auditFlowStepModel->getError());
        }

        //操作日志
        admin_log($data['step_name'], 'edit', 'audit_flow_step');

        $this->success("保存成功！", url("audit_flow_step/index",['audit_id'=>$data['audit_id']]));
    }

    /**
     * 删除审核步骤
     * @adminMenu(
     *     'name'   => '删除审核步骤',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '删除审核步骤',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
        $id = $this->request->param('id', 0, 'intval');

        $auditFlowStepModel = new AuditFlowStepModel();
        
        $auditInfo = $auditFlowStepModel->where('step_id', $id)->find();
        $result    = $auditFlowStepModel->where('step_id', $id)->delete();

        if ( $result!=false ){
            $this->sortIndex($auditInfo['audit_id']);

            //操作日志
            admin_log($auditInfo['step_name'], 'edit', 'audit_flow_step');

            $this->success("删除成功！");
        }else{
            $this->error("删除失败");
        }
    }

    public function sortIndex($audit_id=''){
        //创建步骤序号排列
        $auditFlowStepModel = new AuditFlowStepModel();

        $where = [];
        if( !empty($audit_id) ){
            $where['audit_id'] = $audit_id;
        }

        $stepList = $auditFlowStepModel
                 -> field('step_id, step_index')
                 -> where($where)
                 -> order('step_id asc')
                 -> select()
                 -> toArray();
                 
        if( empty($stepList) )  return;

        foreach ($stepList as $k => $v) {
            $stepList[$k]['step_index'] = $k+1;
        }
        $auditFlowStepModel->saveAll($stepList);

        return count($stepList);
    }
}
